<template>
  <div class="container">
    <div class="tabber">
      <a-space size="medium" direction="vertical" fill>
        <a-space>
          <a-input placeholder="请输入id搜索" v-model="search"></a-input>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <icon-search />
            </template>
            <template #default>搜索</template>
          </a-button>
        </a-space>
        <a-space>
          <!-- <a-button
            type="primary"
            @click="
              visible = true;
              isAdd = true;
              form = {};
              form.type = 1;
              form.status = 1;
            "
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>新增</template>
          </a-button> -->
          <a-button type="primary" @click="handleRefresh">
            <template #icon>
              <icon-loop />
            </template>
            <template #default>刷新</template>
          </a-button>
          <a-button
            type="primary"
            status="warning"
            @click="changeModList = true"
          >
            选择动态
          </a-button>
          <a-button
            status="danger"
            @click="deleteAll = selectedKeys.length > 0 ? true : false"
          >
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
          <a-tag v-if="changeItem.id" size="large" color="blue"
            >&nbsp;&nbsp;&nbsp;动态id：{{ changeItem.id }} - 作者：{{
              changeItem.user.nikeName
            }}&nbsp;&nbsp;&nbsp;</a-tag
          >
          <a-tag v-else color="gray" size="large">未选择动态</a-tag>
        </a-space>
      </a-space>
    </div>
    <a-table
      row-key="id"
      :columns="columns"
      :data="data"
      column-resizable
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      :bordered="{ cell: true }"
      :scroll="{ x: 'min-content' }"
      size="small"
      :table-layout-fixed="true"
    >
      <template #cover="{ record }">
        <a-avatar :imageUrl="BASE_URL + record.user.avatar"> </a-avatar>
      </template>

      <template #optional="{ record }">
        <a-button size="mini" status="danger" @click="deleteHanddle(record)"
          >删除</a-button
        >
      </template>
    </a-table>
  </div>
  <!-- 删除弹框 -->
  <a-modal v-model:visible="delvalue" title="确认删除" @before-ok="delBeforeOk">
    <a-form :model="form">
      <a-form-item field="id" label="ID">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item field="name" label="标题">
        <a-input disabled v-model="form.title" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除已选的 -->
  <a-modal v-model:visible="deleteAll" @before-ok="handleDeleteAll">
    <template #title> 警告 </template>
    <div>是否删除已选 {{ selectedKeys.length }} 项数据？</div>
  </a-modal>
  <!-- 选择器 -->
  <a-modal title="选择竞赛" v-model:visible="changeModList">
    <a-scrollbar type="track" style="height: 400px; overflow: auto">
      <a-input-search
        v-model="filterTxt"
        :style="{ width: '240px', marginBottom: '10px' }"
        placeholder="请输入查询id"
      />
      <a-list>
        <a-list-item v-for="item in filterModList" :key="item.id">
          <a-list-item-meta
            :title="item.title"
            :description="`id：${item.id}-作者:${item.user.nikeName}`"
          >
            <template #avatar>
              <a-avatar shape="square">
                <img
                  v-if="item.atlas[0]"
                  alt="avatar"
                  :src="BASE_URL + item.atlas[0]"
                />
                <img
                  v-else-if="item.videoCover"
                  alt="avatar"
                  :src="BASE_URL + item.videoCover"
                />
              </a-avatar>
            </template>
          </a-list-item-meta>
          <template #actions>
            <a-button type="primary" @click="handleChangeMod(item)">
              选择
            </a-button>
          </template>
        </a-list-item>
      </a-list>
    </a-scrollbar>
  </a-modal>
</template>

<script setup>
import { BASE_URL } from "../../constant/index";
import { reactive, ref, onMounted, computed } from "vue";
import { formatTime } from "../../utils/dataUtils";
import { getDynamicListApi } from "../../api/dynamic";
import { getCommentListApi, deleteCommentApi } from "../../api/comment.js";
import {
  IconPlus,
  IconSearch,
  IconLoop,
  IconDelete,
} from "@arco-design/web-vue/es/icon";

import { Message, Modal } from "@arco-design/web-vue";

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: false,
  onlyCurrent: false,
});
const pagination = { pageSize: 10 };
const columns = [
  {
    title: "id",
    dataIndex: "id",
    fixed: "left",
    width: 150,
    ellipsis: true,
    tooltip: true,
    align: "center",
  },

  {
    title: "头像",
    slotName: "cover",
    width: 80,
    align: "center",
  },
  {
    title: "昵称",
    dataIndex: "user.nikeName",
    width: 120,
    align: "center",
  },
  {
    title: "内容",
    dataIndex: "comment",
    width: "auto",
    align: "center",
  },

  {
    title: "创建时间",
    dataIndex: "createdAt",
    width: 220,
    align: "center",
  },
  {
    title: "操作",
    fixed: "right",
    width: 200,
    slotName: "optional",
    align: "center",
  },
];

const data = ref([]);

// 选择框
const modList = ref([]);
const filterTxt = ref("");
const filterModList = computed(() => {
  return modList.value.filter((item) => {
    if (!filterTxt.value) {
      return true;
    }
    return item.id.includes(filterTxt.value);
  });
});

const changeModList = ref(false);
const changeItem = ref({});

//  获取列表数据
async function getListData() {
  const id = changeItem.value.id;
  const getRes = await getCommentListApi({ id: id });
  console.log(getRes);
  if (getRes.code === 200) {
    data.value = getRes.data;
    if (getRes.data.length == 0) {
      Message.success("暂无评论内容");
    }
  }
}

// 获取所有动态
async function getDynamicList() {
  const getRes = await getDynamicListApi({
    limit: 1000,
    page: 1,
  });
  console.log(getRes.data.list);
  if (getRes.code === 200) {
    modList.value = getRes.data.list;
  }
}
// 选择列表后回调
async function handleChangeMod(item) {
  console.log(item);
  changeItem.value = item;
  // 获取数据
  await getListData();

  // 关闭弹框
  changeModList.value = false;
}

// 获取用户数据
onMounted(() => {
  getDynamicList();
});

// 点击刷新按钮
function handleRefresh() {
  data.value = [];
  getListData();
}
const deleteAll = ref(false);
// 已选择的数据
const selectedKeys = ref([]);
// 点击删除按钮
async function handleDeleteAll(done) {
  console.log(selectedKeys.value);
  const pra = selectedKeys.value.map((id) => {
    return new Promise(async (resolve, reject) => {
      const delRes = await deleteCommentApi({ id });
      console.log(delRes);
      if (delRes.code === 200) {
        resolve(delRes);
      } else {
        reject(delRes);
      }
    });
  });
  try {
    await Promise.all(pra);
    Message.success("批量删除成功");
    done();
    getListData();
  } catch (err) {
    Message.error("批量删除失败");
  }
  console.log("结束");

  return false;
}

const searchType = ref("全部");
const search = ref("");
async function handleSearch() {
  await getListData();
  data.value = data.value.filter((item) => {
    return item.id.includes(search.value);
  });
}

// 显示删除弹框
const form = ref({});

// 删除弹框
const delvalue = ref(false);
// 点击删除按钮
function deleteHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  delvalue.value = true;
}
// 确认删除
async function delBeforeOk() {
  const { id } = form.value;
  console.log(id);
  const delRes = await deleteCommentApi({ id });
  console.log(delRes);
  if (delRes.code === 200) {
    Message.info("删除成功");
    // 更新数据
    getListData();
    delvalue.value = false;
  } else {
    Message.error("删除失败");
    return false;
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 14px;
  box-sizing: border-box;
  .tabber {
    padding-bottom: 14px;
  }
}
</style>
